# -*- coding: UTF-8 -*-
import time

from flask import Blueprint, request, render_template, url_for, session, flash
from werkzeug.utils import redirect

from app import db
from app.db.flow_model import User, Role, RoleMap
from app.db.work_status import TaskStatus, ProcessStatus, UserAction
from app.forms.forms import *

root = Blueprint("admin", __name__)


def init_root_blue(app):
    app.register_blueprint(root, url_prefix="/")

    @app.context_processor
    def include_current_user():
        """
            example:
                zip_to_list(['a','b','c'],[1,2,3])
                :[('a', 1), ('b', 2), ('c', 3)]
        :return:
        """
        return {'current_user': current_user(),
                'task_status': TaskStatus.decode,
                'process_status': ProcessStatus.decode,
                'user_action': UserAction.decode,
                'zip2dict': lambda a,b : dict(zip(a,b)),
                'time_stamp':time.time(),
                }


def current_user():
    if 'account' in session:
        return User.query.filter_by(account=session['account']).first()
    else:
        return None


# @root.before_request
# def is_login():
#     if request.path == "/login" or request.path == "/sign":
#         return None
#     print(session.get("account"))
#     if not session.get("account"):
#         return redirect("/.login")


@root.route('/', methods=['GET'])
def get_root():
    return redirect("/login")


@root.route('/test/', methods=['GET'])
def test():
    return render_template("/layout/test.html")

@root.route('/admin/', methods=['GET'])
def admin():
    return render_template("/layout/admin.html")

@root.route('/logout/', endpoint='logout')
def logout():
    return redirect(url_for('user.logout'))


@root.route('/login/', methods=['GET', 'POST'], endpoint='login')
def login():
    return redirect(url_for("user.login"))


@root.route('/sign/', methods=['GET', 'POST'], endpoint='sign')
def sign():
    return redirect(url_for("user.sign"))


@root.route('/index/', methods=['GET'])
def index():
    return render_template("index.html")


@root.route('/create_role/', methods=['GET', 'POST'])
def create_role():
    user = current_user()
    name = request.form.get('name', None)
    exist = Role.query.filter_by(name=name).first()
    if exist:
        flash("已存在!", 'error')
        return redirect(url_for("admin.roles"))
    else:
        role = Role(name=name)
        db.session.add(role)
        db.session.commit()
        flash("创建成功!", 'ok')
        return redirect(url_for("admin.roles"))


@root.route('/roles/', methods=['GET', 'POST'], endpoint='roles')
def get_roles():
    user = current_user()
    if request.method == 'GET':
        roles = Role.query.all()
        return render_template("roles.html", roles=roles)


@root.route('/update_role/<string:field>/<int:rid>', methods=['GET', 'POST'])
def update_role(field, rid):
    role = Role.query.filter_by(rid=rid).first()
    if field == 'enabled':
        role.enabled = not role.enabled
    elif field == 'name':
        role.name = str(request.form['name'])
    db.session.add(role)
    db.session.commit()
    flash("更新成功!", 'ok')
    return redirect(url_for("admin.roles"))


@root.route('/delete_role/<int:rid>', methods=['GET', 'POST'])
def delete_role(rid):
    role = Role.query.filter_by(rid=rid).first()
    if role:
        name = role.name
        maps = RoleMap.query.filter_by(rid=rid).all()
        for i in maps:
            db.session.delete(i)
        db.session.delete(role)
        db.session.commit()
        flash("删除成功 %s!" % name, 'ok')
        return redirect(url_for("admin.roles"))


@root.route('/role_map/<int:rid>', methods=['GET', 'POST'], endpoint='role_map')
def get_role_map(rid):
    user = current_user()
    if request.method == 'GET':
        role = Role.query.filter_by(rid=rid).first()
        maps = RoleMap.query.filter_by(rid=rid).all()
        users = User.query.filter_by(enabled=True).all()
        return render_template("role_map.html", **locals())


@root.route('/create_role_map/<int:rid>/', methods=['GET', 'POST'])
def create_role_map(rid):
    uid = request.form['uid']
    exist = RoleMap.query.filter_by(rid=rid, uid=uid).first()
    if exist:
        flash("已存在!", 'error')
    else:
        role = RoleMap(rid=rid, uid=uid)
        db.session.add(role)
        db.session.commit()
        flash("创建成功!", 'ok')

    return redirect(url_for("admin.role_map", rid=rid))


@root.route('/delete_role_map/<int:id>/', methods=['GET', 'POST'])
def delete_role_map(id):
    obj = RoleMap.query.filter_by(id=id).first()
    rid = obj.rid
    db.session.delete(obj)
    db.session.commit()
    flash("删除成功!", 'ok')

    return redirect(url_for("admin.role_map", rid=rid))


@root.route('/update_role_map/<string:field>/<int:id>', methods=['GET', 'POST'])
def update_role_map(field, id):
    obj = RoleMap.query.filter_by(id=id).first()
    rid = obj.rid
    if field == 'enabled':
        obj.enabled = not obj.enabled
    db.session.add(obj)
    db.session.commit()
    flash("更新成功!", 'ok')
    return redirect(url_for("admin.role_map", rid=rid))
